package pay

import (
	"strconv"
	"dhfshop/utils/math"
	"dhfshop/models/isv"
	"dhfshop/models/shopping"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego/validation"
	"github.com/pkg/errors"
	"github.com/astaxie/beego"
	"wxsdk/wxpay/customs"
)

// 海关报关管理
type CustomsPayController struct {
	base.BaseController
}

func (this *CustomsPayController) PayAddCustoms() {
	var (
		curAppId   string = ""
		err        error
		acPay      *isv.AcPayParams = nil
		orders     *shopping.ValueOrder = nil
	)
	v := struct {
		Customs      string `form:"customs"  valid:"Required"`
		MchCustomsNo string `form:"mch_customs_no" valid:"Required"`
		OrderId      string `form:"order_id" valid:"Required"`
		CertId       string `form:"cert_id"`
		Name         string `form:"name"`
		Split        int    `form:"split"`
		SubOrderNo   string `form:"sub_order_no"`
	}{Split:0}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
	    beego.Debug(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	orderId, err := strconv.ParseInt(v.OrderId, 10, 64)
	if err != nil {
	    beego.Debug(err.Error())
	    this.ServeError(err.Error())
		return
	}
    curRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	//curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	//partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	//beego.Debug("PayAddCommon payment:", v.Payment)
	if curRoleId == 2 {
	    orders, err = shopping.GetOrderById(orderId)
		if err != nil {
			beego.Debug(err.Error())
			this.ServeError("查询订单信息:" + err.Error())
			return
		}
		curAppId = orders.AppId
		acPay, err = isv.GetParamsByAppIdOrSubAppId(curAppId)
		if err != nil {
			err = errors.Wrap(err, "GetParamsByAppIdOrSubAppId... ")
			beego.Debug(err.Error())
			this.ServeError(err.Error())
			return
		}
	}else{
	    beego.Debug("cur login role is invalid")
	    this.ServeError("cur login role is invalid")
		return
	}
	payment, err := shopping.GetPaymentListByOrderId(orderId)
	if err != nil {
	    beego.Debug(err.Error())
	    this.ServeError("查询支付单信息:" + err.Error())
		return
	}
	request := new(customs.MircopayRequest)
	request.AppId = curAppId
	request.MchId = acPay.SecondMchId
	request.Customs = v.Customs
	request.MchCustomsNo = v.MchCustomsNo
	request.OutTradeNo = v.OrderId
	request.TransactionId = payment.OuterNo
	if v.Split == 1 {
	    request.OrderFee = strconv.FormatInt(math.MultiTotalPriceInt(orders.Payment,100),10) //应付金额
	    request.ProductFee = strconv.FormatInt(math.MultiTotalPriceInt(orders.Payment-orders.PostFee,100),10) //商品价格
	    request.TransportFee = strconv.FormatInt(math.MultiTotalPriceInt(orders.PostFee,100),10) //物流费
	    request.FeeType = "CNY"                              //币种
	    request.SubOrderNo = v.SubOrderNo                    //商户子订单号
	}
	request.CertId = v.CertId
	request.Name = v.Name
	if len(request.CertId) > 3 && len(request.Name) > 2 {
	    request.CertType = "IDCARD"
	}
	rsp, err := customs.MicroAppPay(acPay.SecondAppkey, request)
	if err != nil {
	    beego.Debug(err.Error())
	    this.ServeError(err.Error())
		return
	}
	beego.Debug("cert_check_result:", rsp.CertCheckResult)
	if rsp.CertCheckResult == "DIFFERENT" {
	   //发送模板消息
	   
	}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *CustomsPayController) PayRepushCustoms() {
	var (
		curAppId   string = ""
		err        error
		acPay      *isv.AcPayParams = nil
		orders     *shopping.ValueOrder = nil
	)
	v := struct {
		Customs      string `form:"customs"  valid:"Required"`
		MchCustomsNo string `form:"mch_customs_no" valid:"Required"`
		OrderId      string `form:"order_id" valid:"Required"`
	}{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
	    beego.Debug(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	orderId, err := strconv.ParseInt(v.OrderId, 10, 64)
	if err != nil {
	    beego.Debug(err.Error())
	    this.ServeError(err.Error())
		return
	}
    curRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	//curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	//partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	//beego.Debug("PayAddCommon payment:", v.Payment)
	if curRoleId == 2 {
	    orders, err = shopping.GetOrderById(orderId)
		if err != nil {
			beego.Debug(err.Error())
			this.ServeError("查询订单信息:" + err.Error())
			return
		}
		curAppId = orders.AppId
		acPay, err = isv.GetParamsByAppIdOrSubAppId(curAppId)
		if err != nil {
			err = errors.Wrap(err, "GetParamsByAppIdOrSubAppId... ")
			beego.Debug(err.Error())
			this.ServeError(err.Error())
			return
		}
	}else{
	    beego.Debug("cur login role is invalid")
	    this.ServeError("cur login role is invalid")
		return
	}
	request := new(customs.RepushRequest)
	request.AppId = curAppId
	request.MchId = acPay.SecondMchId
	request.Customs = v.Customs
	request.MchCustomsNo = v.MchCustomsNo
	request.OutTradeNo = v.OrderId
	rsp, err := customs.RepushApp(acPay.SecondAppkey,request,acPay.SecondPemCert,acPay.SecondPemKey)
	if err != nil {
	    beego.Debug(err.Error())
	    this.ServeError(err.Error())
		return
	}
	this.Data["json"] = rsp
	this.ServeJSON()
}
